package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_ID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryBlogById(Long id) {
        // 查询基本信息
        Blog blog = getById(id);
        if(blog==null){
            return Result.fail("未发布笔记");
        }
        // 根据发布者id 获取其姓名 与icon
        setNickNameAndIcon(blog);
        // 查询用户点赞状态
        setIsLiked(blog);
        return  Result.ok(blog);
    }

    private void setIsLiked(Blog blog) {
        //1.获取用户id
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null){
            //未登录
            return;
        }
        Long userId = userDTO.getId();
        //2.判断用户是否点赞
        String key = BLOG_LIKED_ID + blog.getId();
        Double member = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //3.设置点赞状态
        blog.setIsLike(member!=null);
    }

    /**
     * 获取发布者的姓名与icon
     * @param blog 发布笔记对象(包含发布者Id)
     */
    private void setNickNameAndIcon(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public List<Blog> queryHotBlog(Integer current) {
        // 根据分页查询笔记
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            setNickNameAndIcon(blog);
            setIsLiked(blog);
        });
        return records;
    }

    /**
     * 点赞与取消业务
     * @param id 笔记id
     */
    @Override
    public void updateLikedById(Long id) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.判断用户是否点赞
        String key = BLOG_LIKED_ID + id;
        Double member = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(member != null){
            //3.1已点赞
            //3.2数据库点赞数减一
            boolean update = this.update().setSql("liked = liked - 1").eq("id", id).update();
            //3.3redis移除该用户
            if(update){
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }else {
            //4.1未点赞
            //4.2数据库点赞数加一
            boolean update = this.update().setSql("liked = liked + 1").eq("id", id).update();
            //4.3redis添加该用户
            if(update){
                stringRedisTemplate.opsForZSet().add(key, userId.toString(),System.currentTimeMillis());
            }
        }


    }

    /**
     * 查询点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikesById(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY+id;
        //1 从redis Zest数据结构获取点赞用户Id集合
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5==null || top5.isEmpty()){
            // 点赞用户为0
            return Result.ok(Collections.emptyList());
        }
        // 2.解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.ok(userDTOS);
    }

    /**
     * 查询博文的feed流
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key = "blog:feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 4.解析数据：blogId、minTime（时间戳）、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // 4.1.获取id
            ids.add(Long.valueOf(tuple.getValue()));
            // 4.2.获取分数(时间戳）
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else{
                minTime = time;
                os = 1;
            }
        }
        os = minTime == max ? os : os + offset;
        // 5.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Blog blog : blogs) {
            // 5.1.查询blog有关的用户
            setNickNameAndIcon(blog);
            // 5.2.查询blog是否被点赞
            setIsLiked(blog);
        }

        // 6.封装并返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);
    }
}
